package com.websystique.springsecurity.service;

import com.websystique.springsecurity.model.VerificationMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Service("mailService")
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Override
    public boolean sendVerificationMail(VerificationMail verificationMail) {
        boolean b=false;
        MimeMessagePreparator preparator=getMimeMessagePreparator(verificationMail);
        try{
            mailSender.send(preparator);
            b=true;
        }catch (Exception e){e.printStackTrace();}
        return b;
    }
    private MimeMessagePreparator getMimeMessagePreparator(VerificationMail verificationMail) {
        MimeMessagePreparator preparator=new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setFrom("1125502832@qq.com");
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(verificationMail.getEmail()));
                mimeMessage.setText("您好 "+verificationMail.getUsername()+"请在30分钟内激活 逾期无效"+
                verificationMail.getVerficateUrl());
            }
        };
        return  preparator;
    }
}
